<?php
namespace app\api\controller\vppz;

use think\Db;
use think\Cache;
use app\common\library\token\driver\Redis;


use \app\admin\model\vppz\Hospital as HospitalModel;
use \app\admin\model\vppz\Service as ServiceModel;
use \app\admin\model\vppz\HospitalService as HospitalServiceModel;
use \app\admin\model\vppz\Qxzl as QxzlModel;
use \app\admin\model\vppz\Order as OrderModel;
use \app\admin\model\vppz\Staff as StaffModel;
use \app\admin\model\vppz\Slide as SlideModel;
use \app\admin\model\vppz\PhysicalExamPackage as PhysicalExamPackageModel;
use \app\admin\model\vppz\ExaminationOrder as ExaminationOrderModel;
use \app\admin\model\vppz\ExaminationOrderDetail as ExaminationOrderDetailModel;
use \app\admin\model\vppz\PhysicalExam as PhysicalExamModel;
use \app\admin\model\vppz\PhysicalPackageItemRel as PhysicalPackageItemRelModel;

use \addons\vppz\library\Vpower;

class Order extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();

        $this->QxzlModel = new QxzlModel;
		$this->HospitalModel = new HospitalModel;
		$this->ServiceModel = new ServiceModel;
		$this->HospitalServiceModel = new HospitalServiceModel;

		$this->OrderModel = new OrderModel;
        $this->SlideModel = new SlideModel;
		$this->StaffModel = new StaffModel;
		$this->PhysicalExamPackageModel = new PhysicalExamPackageModel;
		$this->ExaminationOrderModel = new ExaminationOrderModel;
		$this->ExaminationOrderDetailModel = new ExaminationOrderDetailModel;
		$this->PhysicalExamModel = new PhysicalExamModel;
		$this->PhysicalPackageItemRelModel = new PhysicalPackageItemRelModel;
    }


    /**
     * 创建订单
     */
    public function create(){
		$area = $this->_area;
		$mine = $this->_mine;


		// 接受参数
		$form = input('form');
		if(empty($form)){
			$this->error("内容填写有误，请重试");
		}
		$form = json_decode(urldecode($form),true);
		if(!$form){
			$this->error("内容填写有误，请重试");
		}

		// 参数验证

		// 验证服务
		if(empty($form['service_id'])){
			$this->error("请选择服务");
		}
		$form['service_id']=intval($form['service_id']);
		//$service = pdo_fetch('SELECT * FROM ' .tablename('vp_pz_service') . ' where  uniacid = :uniacid AND id=:id AND status=1 AND is_del=0 ', array(':uniacid' => $_W['uniacid'],':id'=>$form['service_id']));
		$service = $this->ServiceModel->where(['app_id'=>$this->app_id,'use_switch'=>1])->find($form['service_id']);
		if(empty($service)){
			$this->error('该服务不存在或暂停提供');
		}

		if($service['stype']<100){
			// 验证医院
			if(empty($form['hospital_id'])){
				$this->error("请选择医院");
			}
			$form['hospital_id']=intval($form['hospital_id']);
			//$hospital = pdo_fetch('SELECT id,name,service FROM ' .tablename('vp_pz_hospital') . ' where  uniacid = :uniacid AND city_id=:city_id AND id=:id AND status=1 AND is_del=0 ', array(':uniacid' => $_W['uniacid'],':city_id'=>$city['id'],':id'=>$form['hospital_id']));

			$hospital = $this->HospitalModel->where(['app_id'=>$this->app_id,'use_switch'=>1])->find($form['hospital_id']);
			if(empty($hospital)){
				$this->error('该医院未开通或已暂停服务');
			}

			$hospital['service']=$this->HospitalServiceModel->field('service_id,price')->where(['hospital_id'=>$hospital['id'],'service_id'=>$service['id'],'use_switch'=>1])->find();
			if(empty($hospital['service'])){
				$this->error('该医院尚未支持该服务');
			}
		}

		// 验证就诊时间
		if($service['stype']!=210){
			if(empty($form['starttime'])){
				$this->error("请选择时间");
			}
			$form['starttime']=$form['starttime']/1000;
		}

		if($service['stype']==10 || $service['stype']==15 || $service['stype']==20 ){
			// 验证就诊人
			if(empty($form['client_id']) || empty($form['client_name'])){
				$this->error("请选择就诊人");
			}
			if($service['stype']==15){
				// 接送地址验证
				if(empty($form['address'])){
					$this->error("请填写就诊人所在地址");
				}
			}
		}

		if($service['stype']==30 || $service['stype']==40){
			// 收件地址验证
			if(empty($form['address'])){
				$this->error("请选择收件信息");
			}
		}

		if($service['stype']>100 && $service['stype']<200 ){
			// 验证服务对象
			if(empty($form['client_id']) || empty($form['client_name'])){
				$this->error("请选择服务对象");
			}
			// 服务地址验证
			if(empty($form['address'])){
				$this->error("请填写服务地址");
			}
		}

		// 验证联系方式
		if(empty($form['tel'])){
			$this->error("请填写您的联系方式");
		}

		// 验证费用
		if($service['stype']<100){
			//$hospital['service']=iunserializer($hospital['service']);
			//if(!$hospital['service'][$service['id']] || $hospital['service'][$service['id']]['status']!=1){
			//	$this->error('该医院尚未开通该服务');
			//}
			$form['price']=floatval($form['price']);
			if($form['price']!=$hospital['service']['price']){
				$this->error('服务费用发生变化，请重新下单');
			}
		}elseif($service['stype']>200){
			// 自定义费用不验证
			$form['price']=floor(floatval($form['price'])*100)/100;
		}else{
			$form['price']=floatval($form['price']);
			if($form['price']!=$service['price']){
				$this->error('服务费用发生变化，请重新下单');
			}
		}

		// 分配收益
		// 陪护师收益
		$profit_fee = floor($area['profit']*$form['price'])/100;
		$tax_plat_fee = floor($area['tax_plat']*$form['price'])/100;

		// TODO 需判断有没有团长，没有则为0，由于下单时无法确定，所以团长分佣需在订单完成时重新计算
		$tax_master_fee = floor($area['tax_master']*$form['price'])/100;

		// 判断有没有渠道且在绑定有效期内，没有则为0
		$seller_id=0;
		$tax_seller=0;
		$tax_seller_fee=0;
		if($area['tax_seller']>0 && $mine['seller_id']>0 && ($area['seller_bind']==0 || $area['seller_bind']*86400>(time()-$mine['seller_time']))){
			$seller_id=$mine['seller_id'];
			$tax_seller=$area['tax_seller'];
			$tax_seller_fee = floor($area['tax_seller']*$form['price'])/100;
		}

		// 城市收益（此处计算不准，多扣了团长收益，是否有团长收益需接单时才能确定，所以需在订单完成分佣时重新计算）
		$tax_area_fee = $form['price']-$profit_fee-$tax_plat_fee-$tax_master_fee-$tax_seller_fee;

		// 补全信息，生成订单
		$orderdata=array(
			'app_id'=>$this->app_id,
			'service_id'=>$form['service_id'],
			'service_stype'=>$service['stype'],
			'service_code'=>$form['service_code'],
			'service_name'=>$form['service_name'],
			'service_logo_image'=>$service['logo_image'],
			'hospital_id'=>isset($form['hospital_id'])?$form['hospital_id']:0,
			'hospital_name'=>isset($form['hospital_name'])?$form['hospital_name']:'',
			'area_id'=>$area['id'],
			'area_name'=>$area['name'],
			'title'=>$form['service_name'],
			'user_id'=>$mine['id'],
			'openid'=>$mine['openid'],
			'client_id'=>isset($form['client_id'])?$form['client_id']:0,
			'client_name'=>isset($form['client_name'])?$form['client_name']:'',
			'client_sex'=>isset($form['client_sex'])?$form['client_sex']:0,
			'client_age'=>isset($form['client_age'])?$form['client_age']:0,
			'client_mobile'=>isset($form['client_mobile'])?$form['client_mobile']:'',
			'client_idcard'=>isset($form['client_idcard'])?$form['client_idcard']:'',
			'starttime'=>isset($form['starttime'])?$form['starttime']:0,
			'address'=>isset($form['address'])?serialize($form['address']):'',
			'tel'=>$form['tel'],
			'demand'=>isset($form['demand'])?$form['demand']:'',
			'num'=>Vpower::build_order_num(),
			'price'=>$form['price'],
			'cnt'=>1,
			'amount'=>$form['price'],
			'fee'=>0,
			'cut'=>0,
			'to_pay'=>$form['price'],
			'profit'=>$area['profit'],
			'profit_fee'=>$profit_fee,
			'tax_plat'=>$area['tax_plat'],
			'tax_plat_fee'=>$tax_plat_fee,
			'tax_master'=>$area['tax_master'],
			'tax_master_fee'=>$tax_master_fee,
			'seller_id'=>$seller_id,
			'tax_seller'=>$tax_seller,
			'tax_seller_fee'=>$tax_seller_fee,
			'tax_area_fee'=>$tax_area_fee,
			'createtime'=>time(),
			'status'=>10,
			'status_time'=>time()
		);

		// 是否指定陪诊员（如果指定，直接接单）
		if(isset($form['staff_toid']) && $form['staff_toid']>0){
			$staff_to = $this->StaffModel->where(['app_id'=>$this->app_id,'id'=>$form['staff_toid'],'status'=>20,'stop_switch'=>0])->find();
			if($staff_to){
				$orderdata['staff_toid']=$staff_to['id'];
				$orderdata['staff_touid']=$staff_to['user_id'];
				$orderdata['staff_status']=10;
				$orderdata['staff_id']=$staff_to['id'];
				$orderdata['staff_uid']=$staff_to['user_id'];
				$orderdata['staff_time']=time();
			}
		}


		$ret=$this->OrderModel->save($orderdata);
		$orderdata['id'] = $this->OrderModel->id;
		if(empty($ret) || empty($orderdata['id'])){
			$this->error('抱歉，下单失败，重试看看呢');
		}

		$pay_params = \addons\epay\library\Service::submitOrder([
			'amount'=>$orderdata['to_pay'],
			'orderid'=>'SEV_'.$orderdata['id'],
			'type'=>"wechat",
			'title'=>$orderdata['title'],
			'notifyurl'=>$this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
			//'returnurl'=>"返回地址",// 小程序前端直接反馈无需返回地址页面
			'method'=>"miniapp",
			'openid'=>$orderdata['openid']
			//'auth_code'=>rand(1000,9999);
		]);

		$this->success('下单成功',array(
			'order_id'=>$orderdata['id'],
			'pay_params'=>$pay_params
		));
    }
    /**
     * 设备租赁订单
     */
    public function shebei(){
        $mine = $this->_mine;
        // 接受参数
		$form = input('form');
        $equipmentId = input('equipmentId');
        $calculate = input('calculate');
		if(empty($form) || empty($equipmentId)){
			$this->error("内容填写有误，请重试");
		}
		$form = json_decode(urldecode($form),true);
		$calculate = json_decode(urldecode($calculate),true);
		if(!$form || !$calculate){
			$this->error("内容填写有误，请重试");
		}
        // 验证联系方式
		if(empty($form['contactPhone'])){
			$this->error("请填写您的联系方式");
		}
        $detail = $this->QxzlModel->find($equipmentId);
        // 补全信息，生成订单
		$orderdata=array(
			'app_id'=>$this->app_id,
			'service_id'=>0,
			'equipment_id'=>$equipmentId,
			'saletype'=>$form['saletype'],
			'service_stype'=>'0',
			'service_code'=>'',
			'service_name'=>$detail['name'],
			'service_logo_image'=>$detail['image_url'],
			'hospital_id'=>0,
			'hospital_name'=>'',
			'area_id'=>0,
			'area_name'=>'',
			'title'=>$detail['name'],
			'user_id'=>$mine['id'],
			'openid'=>$mine['openid'],
			'client_id'=>isset($form['client_id'])?$form['client_id']:0,
			'client_name'=>isset($form['client_name'])?$form['client_name']:'',
			'client_sex'=>isset($form['client_sex'])?$form['client_sex']:0,
			'client_age'=>isset($form['client_age'])?$form['client_age']:0,
			'client_mobile'=>isset($form['client_mobile'])?$form['client_mobile']:'',
			'client_idcard'=>isset($form['client_idcard'])?$form['client_idcard']:'',
			'starttime'=>isset($form['starttime'])?$form['starttime']:0,
			'address'=>isset($form['address'])?serialize($form['address']):'',
			'tel'=>$form['contactPhone'],
			'demand'=>isset($form['demand'])?$form['demand']:'',
			'num'=>Vpower::build_order_num(),
			'price'=>$detail['price'],
			'cnt'=>1,
			'amount'=>$calculate['rentFee']??0,
			'fee'=>0,
			'cut'=>$form['days'],
			'to_pay'=>$calculate['total'],
			'profit'=>0,
			'profit_fee'=>0,
			'tax_plat'=>'',
			'tax_plat_fee'=>0,
			'tax_master'=>'',
			'tax_master_fee'=>0,
			'seller_id'=>0,
			'tax_seller'=>0,
			'tax_seller_fee'=>0,
			'tax_area_fee'=>0,
			'createtime'=>time(),
			'status'=>10,
			'status_time'=>time(),
            'name'=>$form['contactName'],
            'content'=>json_encode(input())
		);

		$ret=$this->OrderModel->save($orderdata);
		$orderdata['id'] = $this->OrderModel->id;
		if(empty($ret) || empty($orderdata['id'])){
			$this->error('抱歉，下单失败，重试看看呢');
		}

		$pay_params = \addons\epay\library\Service::submitOrder([
			'amount'=>$orderdata['to_pay'],
			'orderid'=>'QXZL_'.$orderdata['id'],
			'type'=>"wechat",
			'title'=>$orderdata['title'],
			'notifyurl'=>$this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
			//'returnurl'=>"返回地址",// 小程序前端直接反馈无需返回地址页面
			'method'=>"miniapp",
			'openid'=>$orderdata['openid']
			//'auth_code'=>rand(1000,9999);
		]);

		$this->success('下单成功',array(
			'order_id'=>$orderdata['id'],
			'pay_params'=>$pay_params
		));
    }

    /**
     * 体检预约
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function appointment(){
        $mine = $this->_mine;
        // 接受参数
		$form = input('form');
        $selectedItems = input('selectedItems');
        $calculate = input('calculate');
        $packageId= input('packageId');
		if(empty($form) || empty($selectedItems) || empty($packageId)){
			$this->error("预约信息有误，请重试");
		}
		$form = json_decode(urldecode($form),true);
		$selectedItems = json_decode(urldecode($selectedItems),true);

		$calculate = json_decode(urldecode($calculate),true);
		if(!$form || empty($selectedItems)){
			$this->error("预约信息有误，请重试");
		}
        // 验证联系方式
		if(empty($form['name']) || empty($form['phone']) || empty($form['idCard']) || empty($form['selectedDate'])){
			$this->error("预约信息有误，请重试");
		}
        $detail = $this->PhysicalExamPackageModel->find($packageId);
        // 补全信息，生成订单
		$orderdata=array(
            'user_id'=>$mine['id'],
            'openid'=>$mine['openid'],
            'order_no'=>uniqid('tijian_', true),
			'app_id'=>$this->app_id,
            'package_id'=>$packageId,
            'total_price'=>$calculate,
            'pay_price'=>$calculate,
            'hospital_id' => empty($detail) ? '' : $detail->hospital_id,
            'hospital_name' => empty($detail) ? '' : $detail->hospital_name,
            'hexiao_hospital_id' => empty($detail) ? '' : $detail->hospital_id,
            'hexiao_hospital_name' => empty($detail) ? '' : $detail->hospital_name,
            'hospital_level' => empty($hospital) ? '' : $hospital->rank,
            'hospital_address' => empty($hospital) ? '' : $hospital->address,
            'package_name' => $detail->name,
            'package_people_type' => $detail->people_type,
            'package_original_price' => $detail->total_original_price,
            'package_discount' => $detail->total_discount,
            'package_final_price' => $detail->final_price,
            'exam_person_name' => $form['name'],
            'exam_person_phone' => $form['phone'],
            'exam_person_idcard' => $form['idCard'],
            'exam_date' => $form['selectedDate'],
            'exam_time_slot' => $form['selectedTime'],
            'remark' => $form['remark'],
            'pay_type'=>1
		);
        $opera = [];
        $this->ExaminationOrderModel->startTrans();
		$opera[] =$this->ExaminationOrderModel->save($orderdata);
		$orderdata['id'] = $this->ExaminationOrderModel->id;
        //订单详情
        if(empty($selectedItems) === FALSE){
            $hospital = [];
            if (empty($detail->hospital_id) === FALSE){
                $hospital = $this->HospitalModel->find($detail->hospital_id);
            }
            $num = 0;
            foreach ($selectedItems as &$v){
                $itemData = $this->PhysicalExamModel->find($v);
                $itemRel = $this->PhysicalPackageItemRelModel->where(array(
                    'item_id'=>$v,
                    'package_id'=>$packageId
                ))->find();
                if(empty($itemData) === FALSE && empty($itemRel) === FALSE) {
                    $num++;
                    $orderdetail = array(
                        'order_id' => $orderdata['id'],
                        'order_no' => $orderdata['order_no'],
                        'item_id' => $v,
                        'item_name' => $itemData->name,
                        'item_price' => $itemData->price,
                        'item_discount' => $itemRel->item_discount,
                        'item_description' => $itemData->description,
                        'order_status' => 0
                    );
                    $opera[] = $this->ExaminationOrderDetailModel->insert($orderdetail);
                }
            }
            if($num == 0){
                $opera[] = false;
                $this->ExaminationOrderModel->rollback();
                $this->error('抱歉，至少选中一种体检项');
            }
        }else{
            $opera[] = false;
            $this->ExaminationOrderModel->rollback();
            $this->error('抱歉，至少选中一种体检项');
        }
		if(!\Tools::checkArrayResult($opera)){
            $this->ExaminationOrderModel->rollback();
			$this->error('抱歉，下单失败，重试看看呢');
		}
        $pay_params = [];
        $canpay = 0;
        if($calculate > 0) {
            $this->ExaminationOrderModel->commit();
            $pay_params = \addons\epay\library\Service::submitOrder([
                'amount' => $orderdata['pay_price'],
                'orderid' => 'tijian_' . $orderdata['id'],
                'type' => "wechat",
                'title' => $form['name'] . '的体检订单',
                'notifyurl' => $this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
                'method' => "miniapp",
                'openid' => $orderdata['openid']
            ]);

            $canpay = 1;
        }else{
            $userInfo = Db::name('vppz_user')->where(['app_id'=>$this->app_id,'id'=>$mine['id']])->find();
            if(empty($userInfo) === FALSE){
                $redis = new Redis();
                $key = "bangyetang_qipao_info";

                $redis->lpush($key,json_encode(array(
                    'user'=>$userInfo->nickname,
                    'action'=>'购买了体检套餐'
                )));
            }

            $content = '用户:'.$userInfo->nickname.'购买了体检套餐';
            hook('send_message', [1, 'system', '体检套餐', $content]);
            $redis = new Redis();
            $key = 'system_msg_key';

            $redis->lpush($key,1);
            hook('send_message', [$mine['id'], 'user', '体检套餐', $content]);
            \TempNotice::tijiantoadmin($content);
        }

		$this->success('下单成功',array(
			'order_id'=>$orderdata['id'],
			'pay_params'=>$pay_params,
            'canpay'=>$canpay
		));
    }
	/**
     * 订单延迟付款
     */
    public function pay(){
		$cfg=$this->_cfg;
		$mine=$this->_mine;

		$oid = input('oid');
		if(empty($oid)){
			$this->error( '缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->find($oid);
		if(empty($order)){
			$this->error( '该订单不存在');
		}

		if($order['status']!=10){
			$this->error('该订单已过期失效，请重新下单');
		}

		$pay_params = \addons\epay\library\Service::submitOrder([
			'amount'=>$order['to_pay'],
			'orderid'=>'SEV_'.$order['id'],
			'type'=>"wechat",
			'title'=>$order['title'],
			'notifyurl'=>$this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
			//'returnurl'=>"返回地址",// 小程序前端直接反馈无需返回地址页面
			'method'=>"miniapp",
			'openid'=>$order['openid']
			//'auth_code'=>rand(1000,9999);
		]);

		$this->success('', $pay_params);
	}



	/**
     * 订单详情
     */
    public function detail(){
		$cfg=$this->_cfg;
		$mine=$this->_mine;

		$oid = input('oid');
		if(empty($oid)){
			$this->error( '缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->find($oid);
		if(empty($order)){
			$this->error( '该订单不存在');
		}

		// 支付超时自动取消
		if($order['status']==10){
			if($order['status_time']>=(time()-intval($cfg['pay_exp'])*60)){
				// 未超时，计算还有多久超时
				$order['_exp_time']=intval($cfg['pay_exp'])*60 - (time()-$order['status_time']);
			}else{
				// 超时，自动取消
				$orderUp=array(
					'status'=>40,
					'status_time'=>time()
				);

				//$ret=pdo_query('UPDATE '.tablename('vp_pz_order') .' SET status=:status,status_time=:status_time where uniacid=:uniacid and id=:id AND uid=:uid AND status=10 AND status_time=:status_time_old', array(':uniacid' => $_W['uniacid'],':id' => $order['id'],':uid'=>$mine['uid'],':status_time_old'=>$order['status_time'],':status'=>$orderUp['status'],':status_time'=>$orderUp['status_time']));

				$ret = $this->OrderModel->save($orderUp,['app_id'=>$this->app_id,'user_id'=>$mine['id'],'status_time'=>$order['status_time'],'id'=>$order['id']]);

				if($ret>0){
					$order['status']=$orderUp['status'];
					$order['status_time']=$orderUp['status_time'];
				}
			}
		}

		// 处理订单内容
		if($order['address']){
			$order['address']=unserialize($order['address']);
		}

		// 如果订单被接单，获取服务者信息
		if($order['staff_status']==10){
			$order['_staff'] = $this->StaffModel->field('id,user_id,nickname,avatar,sex,age,mobile')->where(['app_id'=>$this->app_id,'id'=>$order['staff_id']])->find();
		}

		$this->success('',array(
			'now'=>time(),
			'order'=>$order,
			//'config'=>$config,
			//'pw'=>$pw
		));

	}

	/**
     * 订单列表
     */
    public function orderlists(){
		$cfg=$this->_cfg;
		$area=$this->_area;
		$mine=$this->_mine;

        // 幻灯
		$slides = $this->SlideModel->field('id,pic_image,stype,stype_link,title')
            ->where(['app_id'=>$this->app_id,'use_switch'=>1,'area_id'=>$area['id'],'channel'=>2])
            ->order('weigh', 'desc')->select();
		// 我的订单
		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=20;

		$where=[
			'app_id'=>$this->app_id,
			'user_id'=>$mine['id']
		];

		// 全部，待支付，进行中，已完成，已取消
		$filt = input('filt');
		if(!empty($filt)){
			$filt=intval($filt);
			// 1 已提交待处理
			// 2 投诉有效并已处理
			// 3 投诉无效
			$where['status']=$filt;
		}

		$list = $this->OrderModel->where($where)->limit($start,$limit)->order('status_time','DESC')->select();


		// 获内容记录
		//$list =  pdo_fetchall('SELECT * FROM ' .tablename('vp_pz_order') . ' WHERE '. $where .' ORDER BY status_time DESC '.' limit '.$start.','.$limit.' ',$params);

		for($i=0;$i<count($list);$i++){
			//$list[$i]['service_logo']=VP_IMAGE_URL($list[$i]['service_logo']);

			// 支付超时取消判断
			if($list[$i]['status']==10 && ($list[$i]['status_time']>=(time()-intval($cfg['pay_exp'])*60))){
				$list[$i]['_exp_time']=intval($cfg['pay_exp'])*60 - (time()-$list[$i]['status_time']);
			}
            //设备详情
            if($list[$i]['service_stype'] == '0'){
                $detail = $this->QxzlModel->find($list[$i]['service_id']);
                $address = unserialize($list[$i]['address']);
                $detail['address'] = $address;
                $list[$i]['qxzl'] = $detail;
            }
		}

		$more=1;
		if(empty($list) || count($list)<$limit){
			$more=0;
		}
		$start+=count($list);

		$this->success('',array(
			'now'=>time(),
			'list'=>$list,
            'slide'=>$slides,
			'start'=>$start,
			'more'=>$more
		));
	}



	/**
     * 取消订单（并自动退款）
     */
    public function cancel(){
		$cfg=$this->_cfg;
		$mine=$this->_mine;

		$oid = input('oid');
		if(empty($oid)){
			$this->error( '缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->find($oid);
		if(empty($order)){
			$this->error('该订单不存在');
		}

		if($order['status']==30){
			$this->error('该订单已完成，不能取消，如有疑问可联系客服');
		}
		if($order['status']==40){
			$this->error('该订单已取消了，请勿重复操作，如有疑问可联系客服');
		}
		if($order['status']==20 && $order['staff_status']==10){
			$this->error('该订单正在服务中，如仍需取消请联系该订单服务专员或客服');
		}

		// 订单状态验证通过，开始取消
		// 更新订单状态
		$orderUp=array(
			'status'=>40,
			'status_time'=>time()
		);
		$ret = $this->OrderModel->save($orderUp,['app_id'=>$this->app_id,'user_id'=>$mine['id'],'status_time'=>$order['status_time'],'id'=>$order['id']]);

		if(!($ret>0)){
			$this->error('操作失败，请重试');
		}

		// 如果已付款生效，则记录取消订单数
		if($order['status']==20){
			Db::name('vppz_user')->where(['app_id'=>$this->app_id,'id'=>$mine['id']])->inc('orders_cancel',1)->update();
		}

		// 如果已经支付，则需要退款
		if($order['status']==20 && $order['pay']>0){
			$refund_fee = $order['pay'];
			$refund_remark = '客户取消订单自动退款';

			$orderUp=array(
				'refund_status'=>1,
				'refund_money'=>$refund_fee
			);
			$ret = $this->OrderModel->save($orderUp,['app_id'=>$this->app_id,'user_id'=>$mine['id'],'refund_status'=>0,'id'=>$order['id']]);

			if(!($ret>0)){
				$this->error('退款失败，请联系客服处理');
			}

			// 1,实施退款
			// 2,更新订单状态为已退款
			$payConfig = \addons\epay\library\Service::getConfig('miniapp');
			$refundRet = \Yansongda\Pay\Pay::wechat($payConfig)->refund([
				'out_trade_no' => 'SEV_'.$order['id'],
				'out_refund_no' => time(),
				'total_fee' => $order['pay']*100,	// 退款单位是分
				'refund_fee' => $refund_fee*100,	// 退款单位是分
				'refund_desc' => $refund_remark,
				'type'=>'miniapp'
			]);

			if(!$refundRet || $refundRet['return_code']!='SUCCESS' || $refundRet['result_code']!='SUCCESS'){
				$this->OrderModel->save(['refund_status'=>3,'refund_tag'=>serialize($refundRet),'refund_time'=>time()],['app_id'=>$this->app_id,'user_id'=>$mine['id'],'refund_status'=>1,'id'=>$order['id']]);
				$this->error('自动退款失败，请联系客服处理：'.$refundRet['err_code_des']);
			}else{
				$this->OrderModel->save(['refund_status'=>2,'refund'=>$refund_fee,'refund_tag'=>serialize($refundRet),'refund_remark'=>$refund_remark,'refund_time'=>time()],['app_id'=>$this->app_id,'user_id'=>$mine['id'],'refund_status'=>1,'id'=>$order['id']]);
				$this->success('退款将于24小时内原路退回您的账户，请注意查收');
			}

		}else{
			$this->success('感谢您的使用，期待再次为您服务');
		}
	}

}
